/*
* @(#)ParaScanGetAllFolderAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/

package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.RootOperationManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.user.bean.MtmUserRecordUserGroup;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserGroupPermission;
import com.dcivision.user.bean.UserRecordPermission;
import com.dcivision.user.bean.UserRole;
import com.dcivision.user.bean.UserRolePermission;
import com.dcivision.user.dao.MtmUserRecordUserGroupDAObject;
import com.dcivision.user.dao.MtmUserRecordUserRoleDAObject;
import com.dcivision.user.dao.UserGroupPermissionDAObject;
import com.dcivision.user.dao.UserRecordPermissionDAObject;
import com.dcivision.user.dao.UserRoleDAObject;
import com.dcivision.user.dao.UserRolePermissionDAObject;



/**
 * <p>Class Name:       ParaScanGetAllFolderAction.jva    </p>
 * <p>Description:      The list action class for ListUserRecord.jsp</p>
 * @author              Jenny Li
 * @company             DCIVision Limited
 * @creation date       21/05/2004
 * @version             $Revision: 1.6.2.1 $
 */
public class ParaScanGetAllFolderAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.6.2.1 $";

	private Hashtable permissionCache = new Hashtable();
	public static final String DENIED_READ_PERMISSION = "r";
	StringBuffer Folder;
	int runNo=0;
  /**
   *  Constructor - Creates a new instance of ListDmsPublicDocumentAction and define the default listName.
   */
  public ParaScanGetAllFolderAction() {
    super();
    this.setListName("dmsPublicDocumentList");
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.dms.dao.DmsDocumentDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.DMS_PUBLIC_FOLDER);
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
//  Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }
    AbstractSearchForm searchForm=(AbstractSearchForm)form;
    Folder=new StringBuffer();
    runNo=0;
    this.getListData(mapping,searchForm,request,response);
    return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
  }
  /**
   * getListData
   *
   * Override the parent's function. Purpose in create the default personal folder when non-exists,
   * and load the dmsDocument list.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void getListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DmsDocumentDAObject dmsDocumentDAO=new DmsDocumentDAObject(sessionContainer,conn);
	DmsRootDAObject dmsRootDAO=new DmsRootDAObject(sessionContainer,conn);
	DocumentRetrievalManager docRetrievalManager=new DocumentRetrievalManager(sessionContainer,conn);
	// DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    RootOperationManager rootOperationManager = new RootOperationManager(sessionContainer, conn);
    DmsDocument documentRoot = null;
    List folderTreeList=new ArrayList();
    try {
    	String parentID=request.getParameter("parentID");
    	String levelNo=request.getParameter("levelNo");
    	Integer nParentID=new Integer(0);
    	if(!Utility.isEmpty(parentID)){
    	  nParentID=TextUtility.parseIntegerObj(parentID);
    	}
 
    	int nlevelNo=TextUtility.parseInteger(levelNo);
    	StringBuffer prFolder=new StringBuffer();
    	StringBuffer nFolder=new StringBuffer();
    	boolean havePermission = false;
    	String newString="";
    	if(!Utility.isEmpty(parentID) && !"0".equals(parentID)){
    	  if(!Utility.isEmpty(request.getParameter("userRecordID"))){	
    	    havePermission=this.checkHasPermissionOnObject(GlobalConstant.OBJECT_TYPE_DOCUMENT,nParentID, null, "R",request);
    	  }else{
    	  	havePermission=false;
    	  }
    	  if(havePermission){
    	  	DmsDocument dmsDocument=(DmsDocument)dmsDocumentDAO.getObjectByID(nParentID);
    		prFolder.append("<Folder FolderId=\""+dmsDocument.getID()+"\" ParentId=\""+dmsDocument.getParentID()+"\" Name=\""+dmsDocument.getDocumentName()+"\">");		
    	    if(Utility.isEmpty(levelNo)){
    	    	nFolder=this.getFolderTreeByParentIDRootID(nParentID,null,0,request,response);
  	  	    }else{
  	  	      List folderList= dmsDocumentDAO.getListByRootID(nParentID,DmsDocument.FOLDER_TYPE);
  	  	      if(nlevelNo>=folderList.size()){
  	  	        nFolder=this.getFolderTreeByParentIDRootID(nParentID,null,0,request,response);
  	  	      }else{
  	  	        nFolder=this.getFolderTreeByParentIDRootID(nParentID,null,nlevelNo,request,response);
  	  	      }
  	  	    }
    	    prFolder.append(nFolder);
      	    prFolder.append("</Folder>");
    	  }
    	  newString=this.htmlEncode(prFolder.toString());
  	  	  //request.setAttribute("prFolder",newString);
    	}else{
    	  List rootList=dmsDocumentDAO.getListByParentID(new Integer(0),null,DmsDocument.FOLDER_TYPE);
    	  List prRootList=new ArrayList();  
    	  StringBuffer pubFolder=new StringBuffer();
    	  
    	  for(int i=0;i<rootList.size();i++){
    	  	Folder=new StringBuffer();
    	  	runNo=1;
    	  	if(!Utility.isEmpty(request.getParameter("userRecordID"))){
    	  	  havePermission=this.checkHasPermissionOnObject(GlobalConstant.OBJECT_TYPE_DOCUMENT,((DmsDocument)rootList.get(i)).getID(),null,"R",request);		    
    	  	}else{
    	  	  havePermission=false;
    	  	}
    	  	if(havePermission){
    	      prRootList.add(rootList.get(i)); 
    	      Integer pID=((DmsDocument)rootList.get(i)).getID();
    	      pubFolder.append("<Folder FolderId=\""+pID+"\" ParentId=\"0\" Name=\""+((DmsDocument)rootList.get(i)).getDocumentName()+"\">");
    	      if(Utility.isEmpty(levelNo)){
    	      	nFolder=this.getFolderTreeByParentIDRootID(pID,null,0,request,response);
    	      }else{
    	  	    List folderList= dmsDocumentDAO.getListByRootID(pID,DmsDocument.FOLDER_TYPE);
    	  	    if(nlevelNo>=folderList.size()){
    	  	      nFolder=this.getFolderTreeByParentIDRootID(pID,null,0,request,response);
    	  	    }else{
    	  	      nFolder=this.getFolderTreeByParentIDRootID(pID,null,nlevelNo,request,response);
    	  	    }
    	  	  }
    	      pubFolder.append(nFolder);
    	      pubFolder.append("</Folder>");
    	    }
    	  } 
    	  newString=this.htmlEncode(pubFolder.toString());	  
    	}
    	request.setAttribute("folders",newString);
      this.commit(request);
      sessionContainer=null;
      docRetrievalManager.release();
      rootOperationManager.release();

    } catch (ApplicationException appEx) {
      this.rollback(request);
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      this.rollback(request);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }finally{
      conn=null;
    }
  }
  
  public boolean checkHasPermissionOnObject(String objectType, Integer objectID, Integer rootID, String permissionCode,HttpServletRequest request) throws ApplicationException {
    boolean havePermission = false;
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    RootRetrievalManager rootManager = new RootRetrievalManager(sessionContainer, conn);
    DmsRoot root = rootManager.getRootObject(rootID);
    /*if (root==null){
      throw new ApplicationException(DmsErrorConstant.ROOT_LOC_NOT_FOUND);
    }*/
    /*if (DmsRoot.PERSONAL_ROOT.equals(root.getRootType())) { //Personal folder can do everything
      havePermission = true;
    }else{*/

      boolean hasRight = false;
      String permission = null;
      DmsDocument dmsObj = null;
      if (objectID.intValue() != 0) {
        dmsObj = docRetrievalManager.getDocument(objectID);
        try {
          permission = this.getPermission(objectType, objectID,request);
        } catch (ApplicationException appEx) {
          log.error(appEx, appEx);
          permission = "";
        }

        log.debug(" objectID: " + objectID + ", permission: " + permission);

        if (permission.indexOf(permissionCode) < 0) {
          String actionTryToCarryOut = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.permission_" + permissionCode);
          return false;
          //throw new ApplicationException(DmsErrorConstant.HAVE_NO_FUNCTION_PERMISSION, null, actionTryToCarryOut);
        }
      }
      if (objectID.intValue() == 0) {
        try {
          dmsObj = docRetrievalManager.getRootFolderByRootID(rootID);
          permission = permissionManager.getPermission(conn,objectType, dmsObj.getID());
        } catch (ApplicationException appEx) {
          log.error(appEx, appEx);
          permission = "";
        }

        log.debug(" ID: " + dmsObj.getID() + ", permission: " + permission);
        if (permission.indexOf(permissionCode) < 0) {
          String actionTryToCarryOut = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.permission_" + permissionCode);
          return false;
          //throw new ApplicationException(DmsErrorConstant.HAVE_NO_FUNCTION_PERMISSION, null, actionTryToCarryOut);
        }
      }
    //}
    docRetrievalManager.release();
    rootManager.release();
    return true;
  }
  
  public synchronized String getPermission(String objectType, Integer objectID,HttpServletRequest request) throws ApplicationException {
    String result = "";
    Connection conn = null;
    boolean matchRequiredFlag = true;

    try {
      conn = this.getConnection(request);
      String permissionString = this.getPermissionString(conn, objectType, objectID,request);
      permissionString = this.forceToAddPermission(conn, "S", permissionString, objectType, objectID,request);
      log.info("Object Permission ("+objectType+objectID+"):" + permissionString);
      return (permissionString);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
      //conn.close();
     // closeConnection(conn);
    }
  }
  
  private synchronized String getPermissionString(Connection conn, String objectType, Integer objectID,HttpServletRequest request) throws ApplicationException {
    String result = "";
    boolean matchRequiredFlag = true;
    SessionContainer sessionContainer=this.getSessionContainer(request);
    //Connection conn=this.getConnection(request);
    MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAO=new MtmUserRecordUserGroupDAObject(sessionContainer,conn);
	MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAO=new MtmUserRecordUserRoleDAObject(sessionContainer,conn);
	UserRecordPermissionDAObject userRecordPermissionDAO=new UserRecordPermissionDAObject(sessionContainer,conn);
	UserGroupPermissionDAObject userGroupPermissionDAO=new UserGroupPermissionDAObject(sessionContainer,conn);
	UserRolePermissionDAObject userRolePermissionDAO=new UserRolePermissionDAObject(sessionContainer,conn);
	Integer userRecordID=null;
	if(!Utility.isEmpty(request.getParameter("userRecordID"))){
	  userRecordID=TextUtility.parseIntegerObj(request.getParameter("userRecordID"));
    }else{
      userRecordID=sessionContainer.getUserRecordID();
    }
	
    List userGroups=mtmUserRecordUserGroupDAO.getListByUserRecordID(userRecordID);
    List userRoles=mtmUserRecordUserRoleDAO.getUserRoleListByUserRecordID(userRecordID);
    if (this.permissionCache.get(objectType + objectID)!=null) {
      return((String)this.permissionCache.get(objectType + objectID));
    }
    try {
      if (!this.isMatchRequired(conn, objectType, objectID,userRecordID,userGroups,userRoles,request)) {
        matchRequiredFlag = false;
        result = this.DENIED_READ_PERMISSION;
      } else {
        List aUserRoles = userRoles;     
        List aUserGroups = userGroups;     
        // User Role permission.
        if (aUserRoles != null) {
          //UserRolePermissionDAObject userRolePermissionDAO = new UserRolePermissionDAObject(this.sessionContainer, conn);
          for (int i = 0; i < aUserRoles.size(); i++) {
            UserRole userRole = (UserRole) aUserRoles.get(i);
            List funcPerm = userRolePermissionDAO.getListByUserRoleIDObjectTypeObjectID(userRole.getID(), objectType, objectID);
            for (int j = 0; j < funcPerm.size(); j++) {
              UserRolePermission userRolePerm = (UserRolePermission) funcPerm.get(j);
              result = combinePermission(result, userRolePerm.getPermission());
            }
          }
        }
        // User Group permission.
        if (aUserGroups != null) {
         // UserGroupPermissionDAObject userGroupPermissionDAO = new UserGroupPermissionDAObject(this.sessionContainer, conn);
          for (int i = 0; i < aUserGroups.size(); i++) {
            MtmUserRecordUserGroup mtmUserRecordUserGroup = (MtmUserRecordUserGroup) aUserGroups.get(i);
            List funcPerm = userGroupPermissionDAO.getListByUserGroupIDObjectTypeObjectID(mtmUserRecordUserGroup.getUserGroupID(), objectType, objectID);
            for (int j = 0; j < funcPerm.size(); j++) {
              UserGroupPermission userGroupPerm = (UserGroupPermission) funcPerm.get(j);
              result = combinePermission(result, userGroupPerm.getPermission());
            }
          }
        }

        // User Record permission.
        //UserRecordPermissionDAObject userRecordPermissionDAO = new UserRecordPermissionDAObject(this.sessionContainer, conn);
        List funcPerm = userRecordPermissionDAO.getListByUserRecordIDObjectTypeObjectID(userRecordID, objectType, objectID);
        if (funcPerm != null) {
          for (int j = 0; j < funcPerm.size(); j++) {
            UserRecordPermission userRecordPerm = (UserRecordPermission) funcPerm.get(j);
            result = combinePermission(result, userRecordPerm.getPermission());
          }
        }

        // Find parent permission for some object types.
        if (Utility.isEmpty(result)) {
          if (GlobalConstant.OBJECT_TYPE_DOCUMENT.equals(objectType)) {
            com.dcivision.dms.dao.DmsDocumentDAObject docDAO = new com.dcivision.dms.dao.DmsDocumentDAObject(sessionContainer, conn);
            com.dcivision.dms.bean.DmsDocument doc = (com.dcivision.dms.bean.DmsDocument)docDAO.getObjectByID(objectID);

            com.dcivision.dms.dao.DmsRootDAObject rootDAO = new com.dcivision.dms.dao.DmsRootDAObject(sessionContainer, conn);
            com.dcivision.dms.bean.DmsRoot dmsRoot = (com.dcivision.dms.bean.DmsRoot)rootDAO.getObjectByID(doc.getRootID());
            if (dmsRoot!=null) {
              if (com.dcivision.dms.bean.DmsRoot.PERSONAL_ROOT.equals(dmsRoot.getRootType()) && sessionContainer.getUserRecordID().equals(dmsRoot.getOwnerID())) {
                result = "R";
              }
              else if (!Utility.isEmpty(doc.getParentID()) && doc.getParentID().intValue() != 0) {
                result = this.getPermissionString(conn, objectType, doc.getParentID(),request);
              }
            }
          }
        }
      }

      this.permissionCache.put(objectType + objectID, result);
      return result;
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
  }
  
  protected synchronized boolean isMatchRequired(Connection conn, String objectType, Integer objectID, Integer userRecordID,List userGroups,List userRoles,HttpServletRequest request) throws ApplicationException {
    List aUserRoles = userRoles;
    List aUserGroups = userGroups;
    Integer nUserRecordID = userRecordID;
    Hashtable hashRoles = new Hashtable();
    Hashtable hashGroups = new Hashtable();
    SessionContainer sessionContainer=this.getSessionContainer(request);
    try {
      // Retrieve user roles and groups if userRecordID is given.
      if (userRecordID != null) {
        MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAObject = new MtmUserRecordUserRoleDAObject(sessionContainer, conn);
        MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAObject = new MtmUserRecordUserGroupDAObject(sessionContainer, conn);
        UserRoleDAObject userRoleDAO = new UserRoleDAObject(sessionContainer, conn);
        aUserRoles = mtmUserRecordUserRoleDAObject.getUserRoleListByUserRecordID(userRecordID);
        aUserGroups = mtmUserRecordUserGroupDAObject.getUserGroupListByUserRecordID(userRecordID);
        nUserRecordID = userRecordID;
        for (int i = 0; i < aUserGroups.size(); i++) {
          UserGroup tmpUserGroup = (UserGroup) aUserGroups.get(i);
          List userRolesByGroup = userRoleDAO.getListByUserGroupID(tmpUserGroup.getID());
          for (int j = 0; j < userRolesByGroup.size(); j++) {
            if (!aUserRoles.contains(userRolesByGroup.get(j))) {
              aUserRoles.add(userRolesByGroup.get(j));
            }
          }
        }
      }

      // Put the user roles ID of that user into Hash table using role ID as key.
      if (!Utility.isEmpty(aUserRoles)) {
        for (int i = 0; i < aUserRoles.size(); i++) {
          UserRole userRole = (UserRole)aUserRoles.get(i);
          hashRoles.put(userRole.getID(), "Y");
        }
      }

      // Put the user group ID of that user into Hash table using group ID as key.
      if (!Utility.isEmpty(aUserGroups)) {
        for (int i = 0; i < aUserGroups.size(); i++) {
          UserGroup userGroup = (UserGroup)aUserGroups.get(i);
          hashGroups.put(userGroup.getID(), "Y");
        }
      }

      // Initialize permission DAOs.
      UserRolePermissionDAObject userRolePermissionDAO = new UserRolePermissionDAObject(sessionContainer, conn);
      UserGroupPermissionDAObject userGroupPermissionDAO = new UserGroupPermissionDAObject(sessionContainer, conn);
      UserRecordPermissionDAObject userRecordPermissionDAO = new UserRecordPermissionDAObject(sessionContainer, conn);

      // Check required role(s).
      List roleRequiredList = userRolePermissionDAO.getRequiredListByObjectTypeObjectID(objectType, objectID);
      if (!Utility.isEmpty(roleRequiredList)) {
        for (int i = 0; i < roleRequiredList.size(); i++) {
          if (hashRoles.get(((UserRolePermission)roleRequiredList.get(i)).getUserRoleID()) == null) {
            return(false);
          }
        }
      }

      // Check required group(s).
      List groupRequiredList = userGroupPermissionDAO.getRequiredListByObjectTypeObjectID(objectType, objectID);
      if (!Utility.isEmpty(groupRequiredList)) {
        for (int i = 0; i < groupRequiredList.size(); i++) {
          if (hashGroups.get(((UserGroupPermission)groupRequiredList.get(i)).getUserGroupID()) == null) {
            return(false);
          }
        }
      }

      // Check required user(s).
      List userRequiredList = userRecordPermissionDAO.getRequiredListByObjectTypeObjectID(objectType, objectID);
      if (!Utility.isEmpty(userRequiredList)) {
        for (int i = 0; i < userRequiredList.size(); i++) {
          if (!nUserRecordID.equals(((UserRecordPermission)userRequiredList.get(i)).getUserRecordID())) {
            return(false);
          }
        }
      }

      return(true);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
  }
  
  private synchronized String forceToAddPermission(Connection conn, String accessType, String permissionString, String objectType, Integer objectID,HttpServletRequest request) throws ApplicationException {
    SessionContainer sessionContainer=this.getSessionContainer(request);
  	if (!Utility.isEmpty(permissionString)) {
      if (GlobalConstant.OBJECT_TYPE_DOCUMENT.equals(objectType)) {
        com.dcivision.dms.dao.DmsDocumentDAObject docDAO = new com.dcivision.dms.dao.DmsDocumentDAObject(sessionContainer, conn);
        com.dcivision.dms.bean.DmsDocument doc = (com.dcivision.dms.bean.DmsDocument)docDAO.getObjectByID(objectID);
        if (doc.getCreatorID().equals(sessionContainer.getUserRecordID()) ) {
          if (permissionString.indexOf(accessType.toLowerCase())>=0) { //has denied permission
            permissionString = permissionString.replace(accessType.toLowerCase().charAt(0), accessType.toUpperCase().charAt(0));
          }
          if (permissionString.indexOf(accessType.toUpperCase())<0) { //did not assigned with permission
            permissionString = permissionString + accessType;
          }
        }
      }
    }
    return permissionString;
  }
  
  public static String combinePermission(String source, String target) {
    if (Utility.isEmpty(source) && Utility.isEmpty(target)) {
      return null;
    } else if (Utility.isEmpty(source)) {
      return target;
    } else if (Utility.isEmpty(target)) {
      return source;
    } else if (GlobalConstant.PERMISSION_ALL.equals(source)) {
      return source;
    } else if (GlobalConstant.PERMISSION_ALL.equals(target)) {
      return target;
    } else {
      String newPermission = source;
      for (int i=0; i<target.length(); i++) {
        String singlePerm = target.substring(i, i+1);
        boolean bDenyPermission = (source.indexOf(singlePerm.toLowerCase())>=0);
        if (source.toLowerCase().indexOf(singlePerm.toLowerCase())<0 && !bDenyPermission) { //new and non-denied access right
          newPermission += singlePerm;
        } else if (source.toLowerCase().indexOf(singlePerm.toLowerCase())>=0) { //replace the access right anyway, so that can add the denied right
          newPermission = newPermission.replace(singlePerm.toUpperCase().charAt(0), singlePerm.charAt(0));
        }
      }
      return newPermission;
    }
  }
  
  public StringBuffer getFolderTreeByParentIDRootID(Integer parentID, Integer rootID,int levelNo,HttpServletRequest request,HttpServletResponse response) throws ApplicationException {
  	runNo++;
  	SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
  	DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List documentList = dmsDocumentDAO.getListByParentID(parentID, rootID, DmsDocument.FOLDER_TYPE);
    List finalList = new ArrayList();
    List tmpList = null;
    /// JspFactory jspxFactory = JspFactory.getDefaultFactory();
    // PageContext pageContext = jspxFactory.getPageContext(null,(ServletRequest)request,(ServletResponse)response,"", true, 8192, true);
    finalList.addAll(documentList);
    if (!Utility.isEmpty(documentList)) {
  	  for (int i=0; i<documentList.size(); i++) {
  	    DmsDocument doc = (DmsDocument)documentList.get(i);      	  	
  	    Folder.append("<Folder FolderId=\""+doc.getID()+"\" ParentId=\""+doc.getParentID()+"\" Name=\""+doc.getDocumentName()+"\">");
  	    if(levelNo!=0){
  	      if(runNo<=levelNo){	
  	        Folder = getFolderTreeByParentIDRootID(doc.getID(), null,levelNo,request,response);
  	      }
  	    }else{
  	      Folder = getFolderTreeByParentIDRootID(doc.getID(), null,levelNo,request,response);	
  	    }
  	    Folder.append("</Folder>");    	 
  	  }
    }
    dmsDocumentDAO=null;
    return Folder;
  }
  
  public final static String htmlEncode(String s) {
    s = TextUtility.noNull(s);

    StringBuffer str = new StringBuffer();

    for (int j=0; j<s.length(); j++) {
      char c = s.charAt(j);

      // encode standard ASCII characters into HTML entities where needed
      if (c<'\200') {
        switch (c) {
              case '&':
                str.append("&amp;");
                break;
                default:
                str.append(c);
        }
      } else if (c<'\377') { // encode 'ugly' characters (ie Word "curvy" quotes etc)
        String hexChars = new String("0123456789ABCDEF");
        int a = c % 16;
        int b = (c - a) / 16;
        String hex = "" + hexChars.charAt(b) + hexChars.charAt(a);
        str.append("&#x" + hex + ";");
      } else { // add other characters back in - to handle charactersets other than ascii
        str.append(c);
      }
    }

    return str.toString();
  }
  
 /* public final static String noNull(String string) {
    return noNull(string, "");
  }
  
  public final static String noNull(String string, String defaultString) {
    return (stringSet(string)) ? string : defaultString;
  }*/
 


}